import {
  BookModel
} from "../../models/book.js";
import {
  LikeModel
} from "../../models/like.js";

var bookModel = new BookModel();
var likeModel = new LikeModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    book: {},
    comments: [],
    likeStatus: false,
    likeCount: 0,
    posting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中...',
    })
    const bid = options.bid;
    const detail = bookModel.getDetail(bid);
    const comments = bookModel.getComments(bid);
    const likeStatus = bookModel.getLikeStatus(bid);

    Promise.all([detail, comments, likeStatus])
      .then(res => {
        wx.hideLoading();
        this.setData({
          book: res[0].data,
          comments: res[1].data.comments,
          likeStatus: res[2].data.like_status,
          likeCount: res[2].data.fav_nums
        });
      })

    // detail.then(res => {
    //   this.setData({
    //     book: res.data
    //   });
    //   wx.setNavigationBarTitle({
    //     title: this.data.book.title,
    //   })
    // });
    // comments.then(res => {
    //   this.setData({
    //     comments: res.data.comments
    //   })
    // });
    // likeStatus.then(res => {
    //   this.setData({
    //     likeStatus: res.data.like_status,
    //     likeCount: res.data.fav_nums
    //   })
    // });
  },

  onLike: function(event) {
    const like_or_cancel = event.detail.behavior;
    likeModel.like(like_or_cancel, this.data.book.id, 400);
  },

  onFakePost: function(event) {
    this.setData({
      posting: true
    })
  },

  onCancel: function(event) {
    this.setData({
      posting: false
    })
  },

  onPost: function(event) {
    const comment = event.detail.value || event.detail.text;
    if (!comment) return;
    if (comment.length > 12) {
      wx.showToast({
        title: '短评最多12个字',
        icon: 'none'
      })
      return;
    }
    bookModel.postComment(this.data.book.id, comment)
      .then(res => {
        wx.showToast({
          title: '+ 1',
          icon: 'none'
        })
        this.data.comments.unshift({
          content: comment,
          nums: 1
        });
        this.setData({
          comments: this.data.comments,
          posting: false
        })
      })
  },

  touchMove:function(){
    
  }

})